/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.gui.stocksarrival;

import com.kimstore.bean.Item;
import com.kimstore.bean.Product;
import com.kimstore.factory.DaoFactory;
import java.util.ArrayList;

/**
 *
 * @author Administrator
 */
public class AddItemToStocksController {

    private NewStocksController parentController;
    private AddItemToStocksWindow window;
    private Product product;

    public AddItemToStocksController(NewStocksController parent) {
        this.parentController = parent;
    }

    public void displayWindow() {
        window = new AddItemToStocksWindow(this);
        window.displayWindow();
    }

    public void fromWindow(Item item) {
        item.setProduct(product);
        parentController.createAddItemToStocksControllerCallback(item);
    }

    public void createSelectProductController() {
        SelectProductController controller = new SelectProductController(this);
        controller.displayWindow();
    }

    public void createSelectProductControllerCallback(Product product) {
        this.product = product;
        window.populateFieldsWith(product);
    }

    public void validate(Item item) throws Error {
        if (product == null) {
            throw new Error("<html>Please select a <b>Product</b></html>");
        }

        if (item.getSerial().isEmpty()) {
            throw new Error("<html><b>SKU</b> has not been filled up</html>");
        }

        boolean exists = DaoFactory.getInstance().getItemDao().existsSerial(item.getSerial());
        boolean existsInLocal = checkLocalItemSKU(item.getSerial());
        if (exists) {
            throw new Error("<html><b>SKU</b> has already been taken</html>");
        }
        
        if(existsInLocal){
            throw new Error("<html><b>SKU</b> has already been taken</html>");
        }
    }
    
    private boolean checkLocalItemSKU(String SKU){
        for(Item i: parentController.getItems()){
            if(i.getSerial().equals(SKU)) {
                return true;
            }
        }
        return false;
    }
}
